<?php


namespace app\game\middlewares;


use app\common\caches\GameCache;
use app\common\helpers\Response;
use app\common\traits\ApiResponseTrait;
use think\facade\Env;

class ValidateGame
{
    use ApiResponseTrait;

    public function handle($request, \Closure $next)
    {
        $app_id     = $request->post('app_id', '');
        $app_secret = $request->post('app_secret', '');
        $ip         = $request->ip();
        $game = GameCache::getGameByAppId($app_id);
        if (!$game){
            return $this->failed("未找到该游戏信息，app_id：{$app_id}", Response::HTTP_NOT_FOUND);
        }
        if ($game->app_secret != $app_secret){
            return $this->failed('app_secret错误，请查证', Response::HTTP_FORBIDDEN);
        }
        if (Env::get('APP_ENV') == 'product' && is_array($game->access_ips) && count($game->access_ips) > 0 && !in_array($ip, $game->access_ips)){
            return $this->failed('该IP地址未配置', Response::HTTP_FORBIDDEN);
        }
        $request->game_name = $game->name;
        return $next($request);
    }
}
